package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.mapper.OrdersettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTabJc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrdersettingService.class)
@Transactional
public class OrdersettingServiceImpl implements OrdersettingService {

   @Autowired
   private OrdersettingMapper ordersettingMapper;

   //将excel中数据录入到数据库
   public void add(List<OrderSetting> dataList) {
      if (dataList != null && dataList.size() > 0) {
         //1.遍历集合
         for (OrderSetting orderSetting : dataList) {
            //2.调用mapper,查询当前数据是否存在
            Long count = ordersettingMapper.findCountByOrderDate(orderSetting.getOrderDate());
            if (count > 0) { //存在当天数据
               //3.调用mapper,进行编辑
               ordersettingMapper.editNumberByOrderDate(orderSetting);
            } else { //不存在当天数据
               //4.调用mapper,进行插入
               ordersettingMapper.add(orderSetting);
            }
         }
      }
   }

   //通过月份查询预约设置信息
   public List<Map> getOrdersettingByMonth(String date) { //参数格式：2020-10
      //1.设置日期参数
      String dateBegin = date + "-1";
      String dateEnd = date + "-31";
      //2.封装参数为map集合,便于传递
      Map<String,String> map = new HashMap<String,String>();
      map.put("dateBegin", dateBegin);
      map.put("dateEnd", dateEnd);
      //3.根据日期范围进行查询
      List<OrderSetting> list = ordersettingMapper.getOrdersettingByMonth(map);
      //4.遍历list封装返回结果
      List<Map> result = new ArrayList<Map>();
      Map resultMap = null;
      for (OrderSetting orderSetting : list) {
         resultMap = new HashMap<String,Integer>();
         resultMap.put("date",orderSetting.getOrderDate().getDate());
         resultMap.put("number",orderSetting.getNumber());
         resultMap.put("reservations",orderSetting.getReservations());

         //添加result集合
         result.add(resultMap);
      }
      return result;
   }

   //设置根据日期设置可预约数
   public void editNumberByDate(OrderSetting orderSetting) {
      //1.查询当前时间是否已有数据
      Long count = ordersettingMapper.findCountByOrderDate(orderSetting.getOrderDate());

      if (count > 0) {
         //已存在数据,进行修改操作
         ordersettingMapper.editNumberByOrderDate(orderSetting);
      } else {
         //无数据,进行添加操作
         ordersettingMapper.add(orderSetting);
      }

   }
}
